////////////////////////////////////////////////////////////////////////////////
//  COPYRIGHT (C) 2010 TELECOM DIGITAL MEDIA ("TDMEDIA").
//  ALL RIGHTS RESERVED.
//
//  THIS IS CONFIDENTIAL AND PROPRIETARY INTELLECTUAL PROPERTY OWNED BY AND
//  CREATED ON BEHALF OF TDMEDIA. ANY FORM OF DISTRIBUTION, COPY,
//  MODIFICATION WITHOUT THE WRITTEN CONSENT FROM TDMEDIA IS STRICTLY
//  PROHIBITED.
////////////////////////////////////////////////////////////////////////////////
package cc.telecomdigital.tdstock.activity.groups.stock;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import cc.telecomdigital.tdstock.ITDLApplication;
import cc.telecomdigital.tdstock.R;
import cc.telecomdigital.tdstock.Framework.UniqueItem.TDStockLog;
import cc.telecomdigital.tdstock.Http.H_CODE;
import cc.telecomdigital.tdstock.Http.HttpSuperClassStockBaseActivity;
import cc.telecomdigital.tdstock.Http.Services.HttpAppInfo;
import cc.telecomdigital.tdstock.Http.Services.H_HttpServiceRequest.H_UserClient_HttpRequest_Result;
import cc.telecomdigital.tdstock.Tools.ActivityGroupController;
import cc.telecomdigital.tdstock.activity.groups.StockGroup;
import cc.telecomdigital.tdstock.adapter.NewsListItemAdapter;
import cc.telecomdigital.tdstock.adapter.NewsViewHolder;

/**
 * @author haibo for list item named "Instant Market"
 */
public class CurrentStockNewsListActivity extends HttpSuperClassStockBaseActivity
{
	protected static final String		TAG							= CurrentStockNewsListActivity.class.getSimpleName();
	
	public static String				_stockCode					= "";
	private static final long			SPECIAL_ID_LOAD_NEXT		= 80000l;
	private static final long			SPECIAL_ID_LOAD_EOF			= 70000l;
	private static final long			SPECIAL_ID_LOAD_NONE		= 60000l;
	private static final long			START_ID					= 90000l;

//	public static final String			KEY_FOR_CURRENT_STOCK_CODE	= "key.current.code";

	private ListView					_listView;
	private Button						_toolBtnReturn;

	private TextView					_top_bar_title;

	private static NewsListItemAdapter	_newsAdapter;
	private static List<NewsViewHolder>	_newsList;
	private String[]					_newsTitleList;																													// updated
	private String[]					_newsIdList;																														// updated
	private String[]					_timestamp;																														// updated
	private String[]					_vendor;

	public static boolean				_isComeFromBack				= false;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.stock_news);

		_toolBtnReturn = (Button) findViewById(R.id.more_returnbtn);
		_toolBtnReturn.setFocusable(true);
		_toolBtnReturn.setClickable(true);
		_toolBtnReturn.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				TDStockLog.d(TAG, "close current activity and forwarding to the previous");

				// BMP Mode by ouyangzhihui 2011-10-13
				Class<? extends Activity> _cls = CurrentStockInfoActivity.class;
				if (((ITDLApplication) getApplicationContext()).getIsBMPMode())
				{
					_cls = BMPCurrentStockInfoActivity.class;
				}
				Intent intent = new Intent(getApplicationContext(), _cls);
				intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NO_USER_ACTION);

				SwitchForwardActivity(_cls, intent);
			}
		});

		_messageHandler = null; // this activity no need it.
		_listView = (ListView) findViewById(R.id.stock_news_list);

		_top_bar_title = (TextView) findViewById(R.id.top_bar_title);

		_newsList = new ArrayList<NewsViewHolder>();
	}


	private void updateAdapter()
	{
		_listView.setEnabled(true);
		_listView.setClickable(true);
		
		if (!_newsList.isEmpty())
		{
			_newsList.remove(_newsList.size() - 1); // remove the last item for
			// it just a flag mark the
			// news list.
		}

		long id = START_ID + _newsList.size();
		for (int index = 0, listSize = _newsTitleList == null ? 0 : _newsTitleList.length; index < listSize; index++)
		{
			id += index;
			NewsViewHolder viewHolder = new NewsViewHolder();
			viewHolder.id = id;
			viewHolder.newsId = _newsIdList[index];
			viewHolder.vendorId = _vendor[index];
			viewHolder.text = new TextView(this);
			viewHolder.text.setText(_newsTitleList[index]);
			viewHolder.sign = new ImageView(this);
			_newsList.add(viewHolder);
		}
		int theLastItemResouceId = 0;
		if (_newsTitleList == null || _newsTitleList.length < 1 || _newsList.size() < 1)
		{
			id = SPECIAL_ID_LOAD_NONE;
			theLastItemResouceId = R.string.provide_no_information; // modify by zor(ouyangzhihui)
		}
		else if (_newsTitleList.length == 20)
		{
			id = SPECIAL_ID_LOAD_NEXT;
			theLastItemResouceId = R.string.record_tips_next;
		}
		else if (_newsTitleList.length < 20)
		{
			id = SPECIAL_ID_LOAD_EOF;
			theLastItemResouceId = R.string.record_tips_eof;
		}

		// -----create the last item as the mark of the news---------------
		NewsViewHolder viewHolder = new NewsViewHolder();
		viewHolder.id = id;
		viewHolder.text = new TextView(this);
		viewHolder.text.setText(theLastItemResouceId);
		viewHolder.sign = new ImageView(this);
		_newsList.add(viewHolder);
		// -----create the last item as the mark of the news---------------
		if (_listView.getAdapter() == null
		/* || _listView.getAdapter().getCount() < 1 */)
		{
			_newsAdapter = new NewsListItemAdapter(
					LayoutInflater.from(this), _newsList);
			_listView.setAdapter(_newsAdapter);
		}
		else
		{
			_newsAdapter.notifyDataSetChanged();
		}

		_listView.setOnItemClickListener(new OnItemClickListener()
		{
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id)
			{
				if (position != -1)
				{
					if (id == SPECIAL_ID_LOAD_NEXT)
					{
//						new FetchNewsList(CurrentStockNewsListActivity.this.getParent()).execute();
						_isComeFromBack = false;
						progressView.SetShowDialog(false);
						SendHttpRequest();
					}
					else if (id == SPECIAL_ID_LOAD_EOF || id == SPECIAL_ID_LOAD_NONE)
					{
						// do nothing
					}
					else
					{
//						new FetchNewsContext(CurrentStockNewsListActivity.this.getParent()).execute(_newsList.get(position).newsId, _newsList.get(position).vendorId);
						CurrentStockNewsContentActivity.iID = _newsList.get(position).newsId;
						CurrentStockNewsContentActivity.iVendor = _newsList.get(position).vendorId;
						SwitchForwardActivity(CurrentStockNewsContentActivity.class);
					}
				}
			}
		});
	}

	@Override
	protected void onResume()
	{
		if (!_isComeFromBack && !appHost.screenIsLocked)
		{
			resetTitle();
			resetLocalVariable();
		}
		
		progressView.SetShowDialog(true);
		super.onResume();
		_listView.invalidateViews();
	}

	private void resetLocalVariable()
	{
		_newsTitleList = null;
		_newsIdList = null;
		_timestamp = null;
		if (_newsList != null)
			_newsList.clear();
	}

	private void resetTitle()
	{
		_top_bar_title.setText((((ITDLApplication) getApplicationContext()).getCurrentStockName()));
		_top_bar_title.postInvalidate();
	}

	@Override
	public ActivityGroupController GetActivityGroupController()
	{
		return StockGroup.GetActivityGroupHostControl();
	}


	@Override
	protected H_CODE GetDataFromHttpServer()
	{
		if (_isComeFromBack)
			return H_CODE.NONE;
		
		String[] params = HttpAppInfo.GetDataTimeParams(_timestamp, true);

		return HttpAppInfo.SendStockNewsListRequest(actContext, params[0], params[1], _stockCode, this);
	}

	@Override
	public void H_UserClient_HttpRequest_Response_Sub(final H_UserClient_HttpRequest_Result iResult)
	{
		if (iResult.MStatus.equals("0") == false)
		{
			// Prompt Error
			ShowMessageDialog(iResult.MError + "(" + iResult.MStatus + ")");
			return;
		}

//		TDStockLog.d(TAG, "TMP=>Size:" + iResult.contentStores.size());
//		for (String[] tmp : iResult.contentStores)
//		{
//			TDStockLog.d(TAG, "TMP=>" + tmp[0] + "," + tmp[1] + "," + tmp[2] + "," + tmp[3]);
//		}
		
		Runnable runnable = new Runnable()
		{
			public void run()
			{
				updateData(iResult.contentStores);
				
				updateAdapter();
			}
		};
		_messageHandler.post(runnable);
	}

	private void updateData(List<String[]> result)
	{
		_newsTitleList = new String[result.size()];
		_newsIdList = new String[result.size()];
		_timestamp = new String[result.size()];
		_vendor = new String[result.size()];
		
		for (int index = 0; index < result.size(); index++)
		{
			String[] array = result.get(index);
			
			_newsIdList[index] = array[0];
			_newsTitleList[index] = new StringBuffer().append(array[2].substring(0, 16)).append("    ").append(array[1]).toString();
			_timestamp[index] = array[2];
			_vendor[index] = array[3];
			
			TDStockLog.d(TAG, _newsTitleList[index]);
			TDStockLog.d(TAG, _timestamp[index]);
		}
	}

}
